package util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesUtil {
    public static Properties properties = new Properties();
    public static FileInputStream fis = null;
    public static FileOutputStream fos = null;

    /**
     * @param url  要分割的字符串
     * @param path properties文件地址
     */

    public static void storeProperties(String url, String path) {
        String[] strArr = url.substring(url.indexOf("?") + 1).split("&");
        for (int i = 0; i < strArr.length; i++) {
            String[] resultArr = strArr[i].split("=");
            String resultKey = resultArr[0];
            String resultValue = resultArr[1];
            properties.setProperty(resultKey, resultValue);
        }
        try {
            fos = new FileOutputStream(path);//文件名尽量加上properties后缀
            properties.store(fos, null);//store类似与map的put，第二个参数是注释
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void loadProperties(String path) {
        try {
            fis = new FileInputStream(path);
            properties.load(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
